package com.lcredu.service.impl;

import com.lcredu.dao.FurnDAO;
import com.lcredu.dao.OrderDAO;
import com.lcredu.dao.OrderItemDAO;
import com.lcredu.dao.impl.FurnDAOImpl;
import com.lcredu.dao.impl.OrderDAOImpl;
import com.lcredu.dao.impl.OrderItemDAOImpl;
import com.lcredu.entity.*;
import com.lcredu.service.OrderService;

import java.util.*;

/**
 * @author 黎长容
 * @date 2025-07-09 11:41
 */
public class OrderServiceImpl implements OrderService {
    private OrderDAO orderDAO = new OrderDAOImpl();
    private OrderItemDAO orderItemDAO = new OrderItemDAOImpl();
    private FurnDAO furnDAO = new FurnDAOImpl();

    @Override
    public String saveOrder(Cart cart, int memberId) {
        /*
            1.保存订单和订单项
            2.修改furn的销售量和库存
            
            缺点:
                这边我没分析出来需要memberId
                也没分析出来需要修改furn表
                最后还需要清空购物车
         */

        //生成订单会操作多张表,会涉及到事务--->ThreadLocal + Mysql事务机制 + 过滤器 
        //1.订单号
        String orderId = System.currentTimeMillis() + "" + memberId;

        Order order = new Order(orderId, new Date(), cart.getCartTotalPrice(), 0, memberId);
        //保存组装订单
        orderDAO.savaOrder(order);

        //2.通过cart对象遍历items,构建orderItem,并保存
        HashMap<Integer, CartItem> items = cart.getItems();
        Set<Integer> keys = items.keySet();
//        for (Integer key : keys) {
//            CartItem item = items.get(key);
//            OrderItem orderItem = new OrderItem(null, item.getName(), item.getPrice(), item.getCount(), item.getTotalPrice(), orderId);
//            orderItemDAO.savaOrderItem(orderItem);
//
//            //修改furn表
//            Furn furn = furnDAO.selectFurnById(item.getId());
//            furn.setSales(furn.getSales() + item.getCount());
//            furn.setStock(furn.getStock() - item.getCount());
//            furnDAO.updateFurn(furn);
//
//        }


        //第二种遍历方法
        Set<Map.Entry<Integer, CartItem>> entries = items.entrySet();
        for (Map.Entry<Integer, CartItem> entry : entries) {
            CartItem item = entry.getValue();
            OrderItem orderItem = new OrderItem(null, item.getName(), item.getPrice(), item.getCount(), item.getTotalPrice(), orderId);
            orderItemDAO.savaOrderItem(orderItem);

            //修改furn表
            Furn furn = furnDAO.selectFurnById(item.getId());
            furn.setSales(furn.getSales() + item.getCount());
            furn.setStock(furn.getStock() - item.getCount());
            furnDAO.updateFurn(furn);
        }

        //清空购物车
        cart.clear();

        return orderId;
    }

    @Override
    public Order getOrderById(String orderId) {
        return orderDAO.getOrderById(orderId);
    }

    @Override
    public List<OrderItem> getOrderItems(String orderId) {
        List<OrderItem> orderItems = orderItemDAO.getOrderItems(orderId);
        return orderItems;
    }
}
